<?php
session_start();

function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }

    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    if (!is_array($data)) {
        file_put_contents($filename, $defaultContent);
        $data = json_decode($defaultContent, true);
    }

    return $data;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['response'], $_POST['from_user'])) {
    $response = trim(strtolower($_POST['response']));
    $fromUser = htmlspecialchars(trim($_POST['from_user']));
    $currentUser = $_SESSION['username'];

    $users = ensureFile('users.json');
    $messages = ensureFile('messages.json');

    if ($response === 'yes') {
        // 同意好友请求
        foreach ($users as &$user) {
            if ($user['username'] === $currentUser) {
                if (!isset($user['friends'])) {
                    $user['friends'] = [];
                }
                $user['friends'][] = $fromUser;
            }
            if ($user['username'] === $fromUser) {
                if (!isset($user['friends'])) {
                    $user['friends'] = [];
                }
                $user['friends'][] = $currentUser;
            }
        }

        // 发送系统消息通知申请人
        $messages[] = [
            'to_user' => $fromUser,
            'from_user' => '系统消息',
            'message' => "$currentUser 已接受您的好友请求！",
            'status' => 'delivered'
        ];

        file_put_contents('users.json', json_encode($users));
        file_put_contents('messages.json', json_encode($messages));

    } elseif ($response === 'not') {
        // 拒绝好友请求
        $messages[] = [
            'to_user' => $fromUser,
            'from_user' => '系统消息',
            'message' => "$currentUser 拒绝了您的好友请求。",
            'status' => 'delivered'
        ];

        file_put_contents('messages.json', json_encode($messages));
    }

    // 更新请求状态为已处理
    foreach ($messages as &$message) {
        if ($message['from_user'] === $fromUser && $message['to_user'] === $currentUser && $message['status'] === 'pending') {
            $message['status'] = 'processed';
            break;
        }
    }
    file_put_contents('messages.json', json_encode($messages));

    // 返回系统消息页面
    header('Location: system_messages.php');
    exit();
}
?>